package com.csw.compose.ui.module.component.base

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Text
import androidx.compose.material3.TriStateCheckbox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.tooling.preview.Preview
import com.csw.compose.theme.pagePadding
import com.csw.compose.ui.Destination
import com.csw.compose.ui.components.LabelText
import com.csw.compose.ui.components.NormalSpacer
import com.csw.compose.ui.components.UlItem
import com.csw.compose.ui.module.BasePage

@Preview
@Composable
fun CardPagePreview() {
    BasePage({}, "复选框（CheckBox）") {
        CheckBoxPage()
    }
}

class CheckBoxPageData {
    companion object : Destination("CheckBoxPage")
}

/**
 *[参考](https://developer.android.google.cn/develop/ui/compose/components/checkbox?hl=zh-cn)
 */
@Composable
fun CheckBoxPage() {
    Column(
        modifier = Modifier
            .padding(horizontal = pagePadding)
            .verticalScroll(rememberScrollState())
    ) {
        val listCheckedState = remember {
            SnapshotStateList<Boolean>().apply {
                repeat(3) {
                    add(false)
                }
            }
        }
        val checkAllState = when {
            listCheckedState.all { it } -> ToggleableState.On
            listCheckedState.none { it } -> ToggleableState.Off
            else -> ToggleableState.Indeterminate
        }

        Row(verticalAlignment = Alignment.CenterVertically) {
            TriStateCheckbox(checkAllState, {
                val newSate = checkAllState != ToggleableState.On
                listCheckedState.forEachIndexed { index, _ ->
                    listCheckedState[index] = newSate
                }
            })
            Text("全选")
        }

        listCheckedState.forEachIndexed { index, itemChecked ->
            Row(verticalAlignment = Alignment.CenterVertically) {
                Checkbox(itemChecked, {
                    listCheckedState[index] = it
                })
                Text("item $index")
            }
        }

        NormalSpacer()
        UlItem("Checkbox")
        LabelText("复选框，只有选中与未选中状态")
        UlItem("TriStateCheckbox")
        LabelText("三态复选框，多了一种未确定状态，用于表示当前选中了部分选项")
    }
}